package com.bml.architect.seata.service.impl;

import com.bml.architect.seata.consumers.AccountFeignService;
import com.bml.architect.seata.consumers.StorageFeginService;
import com.bml.architect.seata.entity.Order;
import com.bml.architect.seata.entity.OrderStatus;
import com.bml.architect.seata.mapper.OrderMapper;
import com.bml.architect.seata.service.OrderService;
import com.bml.architect.seata.vo.OrderVo;
import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author: baiml
 * @Title: OrderServiceImpl
 * @ProjectName: 中台技术平台
 * @Depart 中台研发部
 * @Description:
 * @date: 2021/5/12 8:37
 */
@Service
public class OrderServiceImpl implements OrderService {
    private Logger logger = LoggerFactory.getLogger(OrderServiceImpl.class);

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private StorageFeginService storageFeginService;

    @Autowired
    private AccountFeignService accountFeignService;

    @GlobalTransactional
    @Override
    public Order saveOrder(OrderVo orderVo) {
        logger.info("+++++++++++++用户下单");

        logger.info("当前 XID: {}", RootContext.getXID());

        //第一步，保存订单信息
        Order order = new Order();
        order.setUserId(orderVo.getUserId());
        order.setCommodityCode(orderVo.getCommodityCode());
        order.setCount(orderVo.getCount());
        order.setMoney(orderVo.getMoney());
        order.setStatus(OrderStatus.INIT.getValue());
        Integer saveOrderRecord = orderMapper.insert(order);
        logger.info("保存订单{}", saveOrderRecord > 0 ? "成功" : "失败");

        //第二步，扣减库存
        storageFeginService.deduct(orderVo.getCommodityCode(), orderVo.getCount());
        //第三步，扣减金额
        accountFeignService.debit(orderVo.getUserId(), orderVo.getMoney());
        //第四步，更新订单状态
        Integer updateOrderRecord = orderMapper.updateOrderStatus(order.getId(), OrderStatus.SUCCESS.getValue());
        logger.info("更新订单id:{} {}", order.getId(), updateOrderRecord > 0 ? "成功" : "失败");
        return order;
    }
}
